#!/usr/bin/env python
# -*- coding: utf-8 -*-


"""
Highlight all the <code mime-type="..."> nodes in the XHTML tree with Pygments.
mimetype can be for instance text/x-python, look in libs/pygments/lexers/_mapping.py
for available mime types.
"""

import xml.dom.minidom
import pygments
import pygments.lexers
import pygments.lexers.dotnet
import pygments.lexers.web
import pygments.formatters

def execute_minidom(server, document, parameters, current_node=None):
	if not current_node:
		current_node = document

	for n in current_node.childNodes:
		if n.nodeType == document.ELEMENT_NODE:
			# Look for nodes <code lexer="...">
			if n.localName == 'code':
				# Read content
				code = ''
				for n2 in n.childNodes:
					if n2.nodeType in (document.TEXT_NODE, document.CDATA_SECTION_NODE):
						code += n2.data

				# Load lexer
				if n.hasAttribute('mime-type'):
					lexer = n.getAttribute('mime-type')
				else:
					lexer = 'text/plain'

				lexer = pygments.lexers.get_lexer_for_mimetype(lexer)

				# Line numbering or not?
				if n.hasAttribute('line-numbers') and n.getAttribute('line-numbers') == 'true':
					linenos = 'inline'
				else:
					linenos = False

				# Call Pygments
				formatter = pygments.formatters.HtmlFormatter(linenos=linenos)
				code = pygments.highlight(code, lexer, formatter).encode('utf-8')

				# Replace code
				while len(n.childNodes) > 0:
					n.removeChild(n.childNodes[0])

				dom2 = xml.dom.minidom.parseString('<?xml version="1.0" encoding="utf-8"?>%s' % code)
				n.appendChild(dom2.getElementsByTagName('div')[0])
			else:
				execute_minidom(server, document, parameters, n)
